# -*- coding: utf-8 -*-
#----------------------------------------------------------------------------#
# kanjiRadicals.py
# ZhihuiJin <zhihuijin@gmail.com>
# vim: ts=4 sw=4 sts=4 et tw=78:
# Fri Feb  9 11:13:03 JST 2007
#
#----------------------------------------------------------------------------#

""" A nice interface to the Kanjidic dictionary.
"""

#----------------------------------------------------------------------------#

from tools.smartCache import  smartLineIter
from tools import kana

from www import settings

import re
from os import path

#----------------------------------------------------------------------------#


#defaultRadkfile = [ path.join(settings.DATA_DIR, 'radkfile') ]
defaultKradfile = [ path.join(settings.DATA_DIR, 'kradfile') ]

#----------------------------------------------------------------------------#

class KanjidicEntry:
    """ A single entry 
    """
    def __init__(self, entryDetails):
        self.__dict__.update(entryDetails)
        return


#----------------------------------------------------------------------------#

class KanjiRadicals(dict):
    """ An interface to parse the  kradfile 
    """

    #------------------------------------------------------------------------#
    # PUBLIC METHODS
    #

    def __init__(self, kradfiles=None):
        """ Constructor.
            @param kradfiles: The kanji radicals files 
        """
        dict.__init__(self)

        if kradfiles is None:
            kradfiles = defaultKradfile

        self._parseKradfile(kradfiles)

        return

    #------------------------------------------------------------------------#
    # PRIVATE METHODS
    #

    def _parseKradfile(self, files):
        """ Parse the kradfile, get the radicals for each kanji
        """
        segmentPattern = re.compile('[^ :]+', re.UNICODE)

        for line in smartLineIter(files):
            if line.startswith('#'):
                continue

            segments = segmentPattern.findall(line.strip())
            kanjiInfo = {}
            kanji = segments[0]
            kanjiInfo['radicals'] = segments[:1]

            kanjidicEntry = KanjidicEntry(kanjiInfo)
            self.__setitem__(kanji, kanjidicEntry)

        return
    #------------------------------------------------------------------------#

#----------------------------------------------------------------------------#




